﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace Ewk.Runtime.Serialization.PositionBased
{
    class PositionBasedEnumSerializer : DatafieldSerializer<PositionBasedDatafieldAttribute>
    {
        public override Type DatafieldType
        {
            get { return typeof(Enum); }
        }

        public override string Serialize(object datafield, PositionBasedDatafieldAttribute datafieldAttribute)
        {
            return Enum.Format(datafieldAttribute.ElementType, datafield, "d");
        }

        public override object Deserialize(string datafield, PositionBasedDatafieldAttribute datafieldAttribute)
        {
            if (string.IsNullOrEmpty(datafield))
            {
                var message = string.Format(CultureInfo.CurrentCulture, ExceptionMessages.CannotDeserializeValue, datafield, datafieldAttribute.ElementType);
                OnDatafieldSerializationFailed(message);

                return int.MinValue;
            }

            long longTest;
            ulong ulongTest;

            if (long.TryParse(datafield, out longTest) || ulong.TryParse(datafield, out ulongTest))
            {
                var result = Enum.Parse(datafieldAttribute.ElementType, datafield);
                if (Enum.IsDefined(datafieldAttribute.ElementType, result))
                {
                    return result;
                }
            }

            var exceptionMessage = string.Format(CultureInfo.CurrentCulture, ExceptionMessages.CannotDeserializeValue, datafield, datafieldAttribute.ElementType);
            OnDatafieldSerializationFailed(exceptionMessage);

            return int.MinValue;
        }
    }
}
